package com.example.administrator.caigou51.request;

import android.text.TextUtils;

import com.ab.util.AbLogUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.example.administrator.caigou51.activity.GBaseActivity;
import com.example.administrator.caigou51.activity.ServerLogActivity;
import com.example.administrator.caigou51.bean.MainDataBean;
import com.example.administrator.caigou51.bean.OtherBean;
import com.example.administrator.caigou51.global.Constant;
import com.example.administrator.caigou51.recyclerCard.basic.MaterialListAdapter;
import com.example.administrator.caigou51.recyclerCard.basic.MaterialListView;
import com.example.administrator.caigou51.recyclerCard.basic.SuperDIYSwipeRefreshLayout;
import com.example.administrator.caigou51.recyclerCard.basic.SuperSwipeRefresh;
import com.example.administrator.caigou51.util.MD5Util;
import com.example.administrator.caigou51.util.ToastUtil;
import com.example.administrator.caigou51.widget.dialog.SweetDialogManager;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.apache.http.Header;
import org.apache.http.HttpEntity;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.Calendar;

/**
 * RequestServerManager下的实现类，负责总过滤后台接口
 *
 * @author xyg
 */
public class RequestServerDIY implements IRequestServer {

    private static RequestServerDIY instance;
    private static AsyncHttpClient httpClient = null;
    public static int RESULT_FALSE = 0;// 后台返回结果为false
    public static int ERROR_EXCEPTION = -1;// 异常
    public static int ERROR_NULL = -2;// 返回对象为空
    public static int ERROR_JSON_NULL = -3;// 后台返回json字符串为空

    public static String ERROR_TIME_OUT = "网络异常，请检查本地网络";
    public static String ERROR_NULL_TIP = "返回对象为空";
    public static String ERROR_JSON_NULL_TIP = "返回json字符串为空";
    public static String ERROR_SERVER_TIP = "连接服务器失败";
    public static String ERROR_NO_KNOWN_TIP = "未知错误";// 未知错误
    public static String ERROR_ENCODING_TIP = "数据编码格式错误";
    public static String ERROR_JSONSYNTAX_TIP = "网络异常，请重试(JSON语法格式出错)";// JSON语法格式出错
    public static String ERROR_EXCEPTION_TIP = "处理异常";
    private static String boundary;
    private final static char[] MULTIPART_CHARS =
            "-_1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();

    private int totalCount;

    public static RequestServerDIY getInstance() {
        if (instance == null) {
            instance = new RequestServerDIY();
        }
        return instance;
    }

    private static AsyncHttpClient getHttpClient(String tokenAct) {

      /*  final StringBuilder buf = new StringBuilder();
        final Random rand = new Random();
        for (int i = 0; i < 30; i++) {
            buf.append(MULTIPART_CHARS[rand.nextInt(MULTIPART_CHARS.length)]);
        }

        boundary = buf.toString();
        */
        if (httpClient == null) {
            httpClient = new AsyncHttpClient();
            httpClient.setTimeout(20000);

        }
        String token;
        Calendar c = Calendar.getInstance();
        int day = c.get(Calendar.DAY_OF_MONTH);
        if (day < 10) {
            token = tokenAct + "0" + day + "yxe";
        } else {
            token = tokenAct + day + "yxe";
        }
        token = MD5Util.stringToMD5(token);
     /*   if (App.getInstance().getToken()!=null) {
            httpClient.addHeader(Constant.SystemContext.TOKEN,AppConfig.getInstance().getToken());
		}*/
        httpClient.addHeader("token", token);
        //  httpClient.addHeader("Content-Type",  "multipart/form-data; boundary=" + boundary);
        return httpClient;
    }

    @Override
    public <T extends IBaseResponse> void handleMethodDIY(final GBaseActivity gBaseActivity, final MaterialListView materialListView, final boolean isLoadMore, final SuperDIYSwipeRefreshLayout swipeRefresh, String url, String tokenAct,
                                                          RequestParams requestParams, final Class<T> instanceClass,
                                                          final ICallBackForRequestServer<T> callBack) {

        if (!isLoadMore) {
            if (swipeRefresh != null) {
                swipeRefresh.setPage(2);
            }
        }
        //listview数据不为空的操作
        if (materialListView != null) {
            MaterialListAdapter materialListAdapter = (MaterialListAdapter) materialListView.getAdapter();
            if (materialListAdapter.getAllList().size() > 0) {
                if (gBaseActivity != null) {
                    gBaseActivity.dismissDialog();
                }

                //如果有数据，不执行动画
                materialListView.setItemAnimator(null);
            } else {
                if (gBaseActivity != null) {
                    gBaseActivity.showLoadingDialog();
                }
            }
        } else {
            if (gBaseActivity != null) {
                gBaseActivity.showLoadingDialog();
            }
        }
        ServerLogActivity.saveRequest2File(requestParams, url);
        //	 getHttpClient().post(AppConfig.getInstance(),url, httpentity, "",
        getHttpClient(tokenAct).post(url, requestParams,
                new AsyncHttpResponseHandler() {
                    String content = "";

                    @Override
                    public void onSuccess(int arg0, Header[] headers, byte[] arg2) {

                        // TODO Auto-generated method stub53ec5c9ba310221b619d07e4
                        try {
                            if (gBaseActivity != null) {

                                gBaseActivity.dismissDialog();
                            }
                            //如果token为空，重新获取
                        
							/*	for (int i = 0; i < headers.length; i++) {
                                    if (App.getInstance().getToken()==null) {
										if (headers[i].getName().equals(Constant.SystemContext.TOKEN)) {
											AppConfig.getInstance().setToken(headers[i].getValue());
										}
									}
									if (headers[i].getName().equals("Set-Cookie")) {
										AppConfig.getInstance().setCookie(headers[i].getValue().split(";")[0]);
									}
								}*/

                            content = new String(arg2, Constant.SystemContext.encodeStyle);
                            if (!TextUtils.isEmpty(content)) {
                                //这里解析jsonRin

                                T result = JSON.parseObject(content, instanceClass);

                                if (result != null) {
                                    if (Constant.SystemContext.SuccessState.equals(result.getCode())) {
                                        if (result.getOther()!=null) {
                                            OtherBean otherBean = JSON.parseObject(result.getOther().toString(), OtherBean.class);
                                            if (otherBean!=null && !TextUtils.isEmpty(otherBean.getTotal()))
                                            totalCount = Integer.parseInt(otherBean.getTotal());
                                        }
                                        callBack.onSuccess(result);
                                        if (materialListView != null) {
                                            MaterialListAdapter materialListAdapter = (MaterialListAdapter) materialListView.getAdapter();

                                        }
                                    } else {
                                        ToastUtil.showToast( result.getMessage() != null
                                                && !TextUtils.isEmpty(result
                                                .getMessage().trim()) ? result
                                                .getMessage()
                                                : ERROR_NO_KNOWN_TIP);
                                        callBack.onFail(
                                                RESULT_FALSE,
                                                result.getMessage() != null
                                                        && !TextUtils.isEmpty(result
                                                        .getMessage().trim()) ? result
                                                        .getMessage()
                                                        : ERROR_NO_KNOWN_TIP, content);
                                    }
                                } else {
                                    callBack.onFail(ERROR_NULL,
                                            ERROR_NULL_TIP, content);
                                }
                            } else {
                                StackTraceElement traceElement = ((new Exception()).getStackTrace())[1];
                                AbLogUtil.e(traceElement.getClassName() + "-" + traceElement.getMethodName(), "返回的信息为空");
                                callBack.onFail(ERROR_JSON_NULL,
                                        ERROR_JSON_NULL_TIP, content);

                            }

                        } catch (UnsupportedEncodingException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (Exception e) {
                            Writer writer = new StringWriter();
                            PrintWriter printWriter = new PrintWriter(writer);
                            e.printStackTrace(printWriter);
                            Throwable cause = e.getCause();
                            while (cause != null) {
                                cause.printStackTrace(printWriter);
                                cause = cause.getCause();
                            }
                            printWriter.close();
                            content += ",异常信息：" + writer.toString();
                            e.printStackTrace();
                            callBack.onFail(ERROR_EXCEPTION,
                                    ERROR_EXCEPTION_TIP, content);

                        } finally {

                            if (swipeRefresh != null) {
                                //加载更多多了一个小圈
                                if (isLoadMore && totalCount>0) {
                                    swipeRefresh.setPage(swipeRefresh.getPage(isLoadMore)+1);
                                }else
                                {
                                    swipeRefresh.setPage(2);
                                }
                                //AbLogUtil.e("first-last", "first-" + firstCount + "-last-" + lastCount);
                                swipeRefresh.updateSwipeRefreshSuccess(totalCount, isLoadMore);

                            }
                            ServerLogActivity.saveResponse2File(content);
                        }
                        //  super.onSuccess(arg0, arg1, arg2);
                    }

                    @Override
                    public void onFailure(int arg0, Header[] arg1, byte[] arg2,
                                          Throwable arg3) {
                        try {
                            if (gBaseActivity != null) {
                                //gBaseActivity.dismissDialog();
                            }
                            if (arg2 != null && arg2.length > 0) {
                                content = new String(arg2, Constant.SystemContext.encodeStyle);
                               /* if (!TextUtils.isEmpty(content)) {
                                    BaseResponse baseResponse = JSONObject.parseObject(content, BaseResponse.class);
                                  //  ToastUtil.showToast(baseResponse.getMessage());
                                    *//*if (baseResponse!=null && Constant.SystemContext.LoginFail.equals(baseResponse.getCode())) {
                                       Intent intent = new Intent();
                         			   intent.setClass(AppConfig.getInstance(), LoginActivity_new.class);
                         			   intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                         			   AppConfig.getInstance().startActivity(intent);
									}*//*
                                }*/

                                callBack.onFail(ERROR_NULL, ERROR_NULL_TIP, content);
                                SweetDialogManager.getInstance().showDialogByErrorTitleText(gBaseActivity, ERROR_NULL_TIP, false, false);
                                // AbToastUtil.showToast(AppConfig.getInstance().getApplicationContext(), ERROR_NULL_TIP);
                            } else {
                                callBack.onFail(ERROR_NULL, ERROR_TIME_OUT, "");
                                SweetDialogManager.getInstance().showDialogByErrorTitleText(gBaseActivity, ERROR_TIME_OUT, false, false);
                                //AbToastUtil.showToast(AppConfig.getInstance().getApplicationContext(), ERROR_TIME_OUT);
                            }


                        } catch (Exception e) {
                            SweetDialogManager.getInstance().showDialogByErrorTitleText(gBaseActivity, ERROR_EXCEPTION_TIP, false, false);
                            //AbToastUtil.showToast(AppConfig.getInstance(),"baseResponse转换错误"+ e.toString());
                            e.printStackTrace();
                        }
//                        catch (JSONException e) {
//                       	 e.printStackTrace();
//						}
                        finally {
                            if (swipeRefresh != null) {
                                //加载更多多了一个小圈
                                if (isLoadMore) {
                                    swipeRefresh.setPage(swipeRefresh.getPage(isLoadMore)-1);
                                }
                                swipeRefresh.updateSwipeRefreshSuccess(0, isLoadMore);

                            }
                            ServerLogActivity.saveResponse2File(content);
                        }
                        // TODO Auto-generated method stub
                        //callBack.onFail(type, errorMsg, json);
                        //ServerLogActivity.saveResponse2File(arg3.getMessage());
                        //   super.onFailure(arg0, arg1, arg2, arg3);
                    }
                });
    }

    @Override
    public <T extends IBaseResponse> void handleMethod(GBaseActivity gBaseActivity, MaterialListView materialListView, SuperSwipeRefresh swipeRefresh, boolean isLoadMore, String url, String TokenAct, RequestParams requestParams, Class<T> instanceClass, ICallBackForRequestServer<T> callBack) {

    }

    @Override
    public <T extends IBaseResponse> void handleMethodGet(GBaseActivity gBaseActivity, MaterialListView materialListView, SuperSwipeRefresh swipeRefresh, boolean isLoadMore, String url, String TokenAct, RequestParams requestParams, Class<T> instanceClass, ICallBackForRequestServer<T> callBack) {

    }



}
